package com.zhugang.week05;

import java.util.HashMap;
import java.util.Map;

/**
 * @program algorithms
 * @description: twoSum
 * @author: chanzhugang
 * @create: 2022/07/07 16:20
 */
public class TwoSum2 {

    /**
     * 1 两数之和
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        // HashMap作为缓存,key存值，value存下标
        Map<Integer, Integer> cache = new HashMap();
        for (int i = 0; i < nums.length; i++) {
            if (cache.containsKey(target - nums[i])) {
                Integer value = cache.get(target - nums[i]);
                return new int[]{i, value};
            }
            cache.put(nums[i], i);
        }
        return new int[]{};
    }
}